<template>
  <div class="app-container">
    <el-table
      v-loading="listLoading"
      :data="usersList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        :label="$t('users.id')"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('users.username')"
        align="center"
      >
        <template slot-scope="{row}">
          <span
            class="link-type"
            @click="handleUpdateClicked(row)"
          >{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('users.avatar')"
        align="center"
      >
        <template slot-scope="{row}">
          <div>
            <el-image
              v-if="row.avatar"
              style="width: 100px; height: 100px"
              :src="row.avatar | resourceFilter"
              :preview-src-list="[row.avatar] | resourcesFilter"
            />
            <span v-else>{{ $t('table.noImage') }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('users.roles')"
        align="center"
      >
        <template slot-scope="{row}">
          <span
            v-for="role in row.roles"
            :key="role"
          >
            {{ role }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('users.gender')"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.gender }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('users.introduction')"
        :show-overflow-tooltip="true"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.introduction }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('res.status')"
        align="center"
      >
        <template slot-scope="{row}">
          <el-tag
            v-if="row.status === UserStatus.ACTIVE"
            type="success"
          >
            {{ $t('users.active') }}
          </el-tag>
          <el-tag
            v-else-if="row.status === UserStatus.BLOCKED"
            type="danger"
          >
            {{ $t('users.blocked') }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="fixed-width"
      >
        <template slot-scope="{row}">
          <el-button
            v-if="row.status === UserStatus.ACTIVE"
            size="mini"
            type="danger"
            @click="handleModifyStatus(row,UserStatus.BLOCKED)"
          >
            {{ $t('users.blocked') }}
          </el-button>
          <el-button
            v-else-if="row.status === UserStatus.BLOCKED"
            size="mini"
            type="success"
            @click="handleModifyStatus(row,UserStatus.ACTIVE)"
          >
            {{ $t('users.blocked') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { CreateQueryParams, QuerySort } from '@nestjsx/crud-request'
import * as _ from 'lodash'
import Pagination from '@/components/Pagination/index.vue'
import { UserRole, UserStatus, CrudPaginatedRes, User, defaultUserData, getUsers, createUser, updateUser } from '@/api'
import { FileListItem, HttpRequestOptions } from 'element-ui/types/upload'
import { elFileListFilter, imageFilenameFilter } from '@/filters'
import { UserModule } from '@/store/modules/user'

@Component({
  name: 'UsersIndex',
  components: {
    Pagination
  }
})
export default class extends Vue {
  private listQuery: CreateQueryParams = {
    sort: [{
      field: 'id',
      order: 'ASC'
    }],
    limit: 20,
    page: 1
  }

  private usersList: User[] = []
  private total = 0
  private listLoading = true
  private dialogFormVisible = false
  private dialogStatus = ''

  private tempUserData = defaultUserData as User
  private tempImagesUploadList: FileListItem[] = []

  private get UserStatus () {
    return UserStatus
  }

  private get header () {
    return {
      'Content-Type': 'multipart/form-data',
      Authorization: 'Bearer ' + UserModule.token
    }
  }

  private get baseApi () {
    return process.env.VUE_APP_BASE_API
  }

  created () {
    this.getList()
  }

  private async getList () {
    const { data } = await getUsers(this.listQuery)
    this.usersList = (data as CrudPaginatedRes<User>).data
    this.total = (data as CrudPaginatedRes<User>).total
    this.listLoading = false
  }

  private handleFilter () {
    this.listQuery.page = 1
    this.getList()
  }

  private sortChange (data: any) {
    const { prop, order } = data
    const index = _.findIndex<QuerySort>(this.listQuery.sort as QuerySort[], { field: prop })

    if (order !== null) {
      if (index !== -1) {
        (this.listQuery.sort as QuerySort[])[index].order = order === 'ascending' ? 'ASC' : 'DESC'
      } else {
        (this.listQuery.sort as QuerySort[]).push({ field: prop, order: 'ASC' })
      }
    } else {
      if (index !== -1) {
        (this.listQuery.sort as QuerySort[]).splice(index, 1)
      }
    }

    this.handleFilter()
  }

  private getSortClass (key: string) {
    const sort = _.find<QuerySort>(this.listQuery.sort as QuerySort[], { field: key })
    return sort && (sort.order === 'ASC' ? 'ascending' : sort.order === 'DESC' ? 'descending' : null)
  }

  private resetTempData () {
    this.tempUserData = _.cloneDeep(defaultUserData) as User
    this.tempImagesUploadList = []
  }

  private async handleModifyStatus (row: User, status: UserStatus) {
    const statusData = { status: status }
    const { data } = await updateUser(row.id, statusData)
    const index = _.findIndex(this.usersList, { id: row.id })
    this.usersList.splice(index, 1, data)
    this.$notify({
      title: '成功',
      message: '用户状态已更新',
      type: 'success',
      duration: 2000
    })
  }
}
</script>
